package ntrees.hu.oauthtest;


import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.HttpAuthHandler;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

//https://graph.renren.com/oauth/authorize?client_id=fee11992a4ac4caabfca7800d233f814&response_type=token&redirect_uri=http://graph.renren.com/oauth/login_success.html

public class AuthActivity extends Activity {
	
	private String TAG = "AuthActivity";
	private String redirectUrl = "http://graph.renren.com/oauth/login_success.html";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		WebView wb = new WebView(this);
		ImageView iv = new ImageView(this);
		ProgressBar pb = new ProgressBar(this);
		iv.setImageResource(android.R.drawable.progress_horizontal);
		setContentView(R.layout.p_activity);
		
		
		wb.setVerticalScrollBarEnabled(false);
		wb.setHorizontalScrollBarEnabled(false);
		wb.getSettings().setJavaScriptEnabled(true);
		wb.setWebViewClient(client);
		wb.clearHistory();
		WebSettings setting = wb.getSettings();
		setting.setSavePassword(false);
		 CookieSyncManager.createInstance(this); 
		 CookieManager cookieManager = CookieManager.getInstance();
		 cookieManager.removeAllCookie();
		 cookieManager.setAcceptCookie(false);
		//wb.loadUrl("https://graph.renren.com/oauth/authorize?client_id=b2585844587c491f89a5303ac23a119d&response_type=token&redirect_uri=http://graph.renren.com/oauth/login_success.html");
	   wb.loadUrl("https://graph.renren.com/oauth/authorize?display=touch&response_type=token&client_id=b2585844587c491f89a5303ac23a119d&redirect_uri=http%3A%2F%2Fgraph.renren.com%2Foauth%2Flogin_success.html");
	}
	
	private WebViewClient client2 = new RenrenWebViewClient();
	private class RenrenWebViewClient extends WebViewClient {

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			Log.d(TAG, "shouldOverrideUrlLoading: Redirect URL: " + url);
			//int b = mListener.onPageBegin(url);
//			switch (b) {
//			case RenrenDialogListener.ACTION_PROCCESSED:
//				RenrenDialog.this.dismiss();
//				return true;
//			case RenrenDialogListener.ACTION_DIALOG_PROCCESS:
//				return false;
//			}
//			getContext().startActivity(
//					new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
//			return true;
			return true;
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			Log.d(TAG, "onPageStarted: Webview loading URL: " + url);
//			boolean b = mListener.onPageStart(url);
//			if (b) {
//				view.stopLoading();
//				RenrenDialog.this.dismiss();
//				return;
//			}
//			super.onPageStarted(view, url, favicon);
//			progress.show();
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			super.onReceivedError(view, errorCode, description, failingUrl);
			Log.d(TAG, "onReceivedError: " + description);
//			mListener.onReceivedError(errorCode, description, failingUrl);
//			progress.hide();
//			RenrenDialog.this.dismiss();
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			Log.d(TAG, "onPageFinished: " + url);
//			mListener.onPageFinished(url);
//			if (showTitle) {
//				String t = view.getTitle();
//				if (t != null && t.length() > 0) {
//					title.setText(t);
//				}
//			}
//			progress.hide();
			setContentView(view);
		}
	}
	
	WebViewClient client =  new WebViewClient() {

		@Override
		public void doUpdateVisitedHistory(WebView view, String url,
				boolean isReload) {
			// TODO Auto-generated method stub
			super.doUpdateVisitedHistory(view, url, isReload);
			Log.d(TAG, "doUpdateVisitedHistory");
		}

		@Override
		public void onFormResubmission(WebView view, Message dontResend,
				Message resend) {
			// TODO Auto-generated method stub
			super.onFormResubmission(view, dontResend, resend);
			Log.d(TAG, "onFormResubmission");
		}

		@Override
		public void onLoadResource(WebView view, String url) {
			// TODO Auto-generated method stub
			super.onLoadResource(view, url);
			Log.d(TAG, "onLoadResource");
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			// TODO Auto-generated method stub
			super.onPageFinished(view, url);
			Log.d(TAG, "onPageFinished: " + view.getUrl());
			//view.getUrl();
			setContentView(view);
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			// TODO Auto-generated method stub
			Log.d(TAG, "onPageStarted: " + url);
            if (url.startsWith(redirectUrl)) {
                Bundle values = parseUrl(url);
                String accessToken = values.getString("access_token");
                if (accessToken != null) {
                	Log.d(TAG, "login ok");
                	Log.d(TAG, values.toString());
                	Toast.makeText(AuthActivity.this, "登录成功！", Toast.LENGTH_LONG).show();
                	Intent it = new Intent();
                	it.putExtras(values);
                	AuthActivity.this.setResult(Activity.RESULT_OK, it);
                	finish();
                	return;
                }
            }
            super.onPageStarted(view, url, favicon);
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			// TODO Auto-generated method stub
			super.onReceivedError(view, errorCode, description, failingUrl);
			Log.d(TAG, "onReceivedError, " + description);
		}

		@Override
		public void onReceivedHttpAuthRequest(WebView view,
				HttpAuthHandler handler, String host, String realm) {
			// TODO Auto-generated method stub
			super.onReceivedHttpAuthRequest(view, handler, host, realm);
			Log.d(TAG, "onReceivedHttpAuthRequest");
		}

		@Override
		public void onReceivedSslError(WebView view,
				SslErrorHandler handler, SslError error) {
			// TODO Auto-generated method stub
			super.onReceivedSslError(view, handler, error);
			Log.d(TAG, "onReceivedSslError");
		}

		@Override
		public void onScaleChanged(WebView view, float oldScale,
				float newScale) {
			// TODO Auto-generated method stub
			super.onScaleChanged(view, oldScale, newScale);
			Log.d(TAG, "onScaleChanged");
		}

		@Override
		public void onTooManyRedirects(WebView view, Message cancelMsg,
				Message continueMsg) {
			// TODO Auto-generated method stub
			super.onTooManyRedirects(view, cancelMsg, continueMsg);
			Log.d(TAG, "onTooManyRedirects");
			Log.d(TAG, "view: " + view.getUrl());
			Log.d(TAG, "continueMsg: " + continueMsg);
			Log.d(TAG, "cancelMsg: " + cancelMsg);
		}

		@Override
		public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
			// TODO Auto-generated method stub
			super.onUnhandledKeyEvent(view, event);
			Log.d(TAG, "onUnhandledKeyEvent");
		}

		@Override
		public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
			// TODO Auto-generated method stub
			Log.d(TAG, "shouldOverrideKeyEvent");
			return super.shouldOverrideKeyEvent(view, event);
		}

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			// TODO Auto-generated method stub
			Log.d(TAG, "shouldOverrideUrlLoading: " + url);
			return super.shouldOverrideUrlLoading(view, url);
		}
		
	};
	
    /**
     * 解析URL中的查询串转换成key-value
     * 
     * @param url
     * @return
     */
    public static Bundle parseUrl(String url) {
        url = url.replace("rrconnect", "http");
        url = url.replace("#", "?");
        try {
            URL u = new URL(url);
            Bundle b = decodeUrl(u.getQuery());
            b.putAll(decodeUrl(u.getRef()));
            return b;
        } catch (MalformedURLException e) {
            return new Bundle();
        }
    }
    
    /**
     * 将用&号链接的URL参数转换成key-value形式。
     * 
     * @param s
     * @return
     */
    public static Bundle decodeUrl(String s) {
        Bundle params = new Bundle();
        if (s != null) {
            params.putString("url", s);
            String array[] = s.split("&");
            for (String parameter : array) {
                String v[] = parameter.split("=");
                if (v.length > 1) {
                    params.putString(v[0], URLDecoder.decode(v[1]));
                }
            }
        }
        return params;
    }
}
